package com.moerlong.platform.service.demo.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.moerlong.platform.service.common.utils.R;

@RefreshScope
@RestController
public class Demo1Controller {
	@Value("${env.name}")  
    private String envName; 
	
	@Value("${env.password}")  
    private String envPassword; 
	
	@Value("${testKey}")  
    private String testKey; 
	
	@Autowired  
    private DiscoveryClient discoveryClient;  
	
    @RequestMapping("/getConfig")
    public R getConfig() {
    	Map map = new HashMap();
    	map.put("envName", envName);
    	map.put("envPassword", envPassword);
    	map.put("testKey", testKey);
        return R.ok().put("config", map); 
    }
    
    @RequestMapping("/demo2")
    public R demo2(@RequestParam String name) {
        return R.ok().put("key1", "values1");
    }
    
    @RequestMapping("/demo3")
    public R demo3(@RequestParam String name) {
        return R.error();
    }
    
    @RequestMapping("/getServices")
    public R getServices() {  
        List list = new ArrayList();
        for( String s :  discoveryClient.getServices()){ 
        	Map map = new HashMap();
        	map.put("serviceName", s);
        	
            System.out.println("services " + s);  
            List<ServiceInstance> serviceInstances =  discoveryClient.getInstances(s);  
            map.put("serviceAttr", serviceInstances);
            for(ServiceInstance si : serviceInstances){  
                System.out.println("    services:" + s + ":getHost()=" + si.getHost());  
                System.out.println("    services:" + s + ":getPort()=" + si.getPort());  
                System.out.println("    services:" + s + ":getServiceId()=" + si.getServiceId());  
                System.out.println("    services:" + s + ":getUri()=" + si.getUri());  
                System.out.println("    services:" + s + ":getMetadata()=" + si.getMetadata());  
            }  
            list.add(map);
              
        }  
          
        return R.ok().put("services", list);
    }
}